package com.cblz.bd.server.core.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cblz.bd.common.core.constant.AdminLoginConstant;
import com.cblz.bd.common.core.constant.BdAdminConstant;
import com.cblz.bd.common.core.entity.BaAdmin;
import com.cblz.bd.common.core.entity.BaAttachment;
import com.cblz.bd.common.core.exception.BdAdminException;
import com.cblz.bd.common.core.utils.BdAdminUtil;
import com.cblz.bd.server.core.annotation.Log;
import com.cblz.bd.server.core.entity.dto.BaAttachmentDTO;
import com.cblz.bd.server.core.entity.vo.BaAttachmentVO;
import com.cblz.bd.server.core.entity.vo.BdAdminTokenVO;
import com.cblz.bd.server.core.event.UploadImageEventListen;
import com.cblz.bd.server.core.mapper.BaAttachmentMapper;
import com.cblz.bd.server.core.service.BaAdminService;
import com.cblz.bd.server.core.service.BaAttachmentService;
import io.vavr.Tuple3;
import io.vavr.control.Option;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author yanjieping
 * @description 针对表【ba_attachment(附件表)】的数据库操作Service实现
 * @createDate 2022-11-04 15:09:53
 */
@Slf4j
@Service("baAttachmentService")
@RequiredArgsConstructor
public class BaAttachmentServiceImpl extends ServiceImpl<BaAttachmentMapper, BaAttachment> implements BaAttachmentService {

    private final BaAdminService baAdminService;

    /**
     * 分页查询附件表信息
     *
     * @param wrapperTuple4 附件实体类
     * @return 分页数据
     */
    @Override
    public Map<String, Object> index(Tuple3<Page<BaAttachment>, QueryWrapper<BaAttachment>, BaAttachmentDTO> wrapperTuple4) {
        Page<BaAttachment> page = wrapperTuple4._1;
        QueryWrapper<BaAttachment> queryWrapper = wrapperTuple4._2;
        BaAttachmentDTO baAttachment = Option.of(wrapperTuple4._3).getOrNull();

        if (Objects.nonNull(baAttachment))
            if (StringUtils.isNotBlank(baAttachment.getAdminNickname())) {
                String adminIds = Option.of(baAdminService.list(new LambdaQueryWrapper<BaAdmin>().like(BaAdmin::getNickname, baAttachment.getAdminNickname()))).getOrElseThrow(() -> new BdAdminException("找不到管理员信息")).stream().map(value -> value.getId().toString()).collect(Collectors.joining(BdAdminConstant.SYSTEM_COMMA.getVal()));
                queryWrapper.in("admin_id", adminIds);
            }

        IPage<BaAttachment> baAttachmentPage = baseMapper.selectPage(page, queryWrapper);
        List<BaAttachmentVO> baAttachmentVOList = new ArrayList<>();
        if (!Objects.isNull(baAttachmentPage) && !baAttachmentPage.getRecords().isEmpty()) {
            baAttachmentPage.getRecords().forEach(val -> {
                BaAttachmentVO baAttachmentVO = BeanUtil.copyProperties(val, BaAttachmentVO.class);
                BdAdminTokenVO bdAdminTokenVO = (BdAdminTokenVO) StpUtil.getSession().get(AdminLoginConstant.SESSION.getValue() + StpUtil.getLoginId());
                int lastIndexOf = val.getName().lastIndexOf(".");
                baAttachmentVO
                        .setSuffix(val.getName().substring(lastIndexOf + 1))
                        .setAdminNickname(bdAdminTokenVO.getNickname())
                        .setUserNickname("")
                        .setQuote(val.getQuote());

                baAttachmentVOList.add(baAttachmentVO);
            });
        }

        return BdAdminUtil.pageResult(baAttachmentVOList, baAttachmentPage.getTotal());
    }

    /**
     * 保存附件信息
     *
     * @param uploadImageEventListen 上传附件的信息，由监听器带过来
     */
    @Override
    @Log(description = "保存附件信息")
    @Transactional(rollbackFor = Exception.class)
    @EventListener(classes = UploadImageEventListen.class)
    public void saveBaAttachment(UploadImageEventListen uploadImageEventListen) {
        Tuple3 source = (Tuple3) uploadImageEventListen.getSource();
        MultipartFile file = (MultipartFile) source._1;
        String objectName = source._2.toString();
        String url = source._3.toString();

        int height = 0, width = 0;
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            height = bufferedImage.getHeight();
            width = bufferedImage.getWidth();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        long nowTime = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));

        BaAttachment baAttachment = new BaAttachment().setAdminId(Integer.parseInt(StpUtil.getLoginId().toString())).setHeight(height).setQuote(1) // 上传次数
                .setName(file.getOriginalFilename()).setSize((double) file.getSize()).setTopic(objectName) // 细目，上传的文件名
                .setWidth(width).setStorage("Minio").setMimetype(file.getContentType()).setUrl(url).setCreatetime(nowTime)
                .setLastuploadtime((int) nowTime);

        save(baAttachment);
    }

    /**
     * 修改附件信息
     *
     * @param baAttachment 实体类
     */
    @Override
    @Log(description = "修改附件信息")
    @Transactional(rollbackFor = Exception.class)
    public void updateBaAttachment(BaAttachment baAttachment) {
        baAttachment.setLastuploadtime((int) LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")));

        updateById(baAttachment);
    }
}




